﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace FillCartridgeBBB.Models
{
    public class FillRepository
    {
        private FillCartridgeDbEntities _db;

        public FillRepository (FillCartridgeDbEntities db)
        {
            _db = db;
        }

        public IEnumerable<Fill> SelectAll()
        {
            return _db.Fills.Include("Customer").Include("Cartridge").Include("Printer").OrderByDescending(f => f.DateOut);
        }
        
        public IEnumerable<Fill> SelectForReturn()
        {
            return _db.Fills.Include("Customer").Include("Cartridge").Include("Printer").Where(f=>!f.DateReturn.HasValue).OrderByDescending(f => f.DateOut);
        }

        public Fill SelectById(int id)
        {
            return _db.Fills.Include("Customer").Include("Cartridge").Include("Printer").First(f => f.FillId == id);
        }

        public void Insert (IEnumerable<Cartridge> Cartridges, string customer)
        {
            int custId = int.Parse(customer);
            Customer cust = _db.CustomerSet.First(c => c.CustomerId == custId);
            foreach (var cartridge in Cartridges)
            {
                Fill fill = new Fill();
                fill.Cartridge = cartridge;
                fill.Printer = cartridge.Printer;
                fill.DateOut = DateTime.Now.Date;
                fill.Customer = cust;
                _db.AddToFills(fill);
             }
             _db.SaveChanges();
        }

        public void Edit(string[] ids, string[] toners, string[] barabans, string[] others, string[] notes)
        {
            for (int i = 0; i < ids.Length; i++)
            {
                int id = int.Parse(ids[i]);
                bool result;
                Fill fill = _db.Fills.First(f => f.FillId == id);
                fill.Toner = bool.TryParse(toners[i], out result) && result;
                fill.Baraban = bool.TryParse(barabans[i], out result) && result;
                fill.Other = others[i];
                fill.Text = notes[i];
            }
            _db.SaveChanges();
        }

        public void Delete (int id)
        {
            Fill fill = _db.Fills.First(f => f.FillId == id);
            _db.DeleteObject(fill);
            _db.SaveChanges();
        }
    }
}
